package com.zshy.base.monitor.infras.config;

import ch.qos.logback.classic.LoggerContext;
import com.google.common.collect.Maps;
import com.zshy.base.monitor.domain.contract.enums.MonitorEnum;
import com.zshy.base.monitor.domain.robot.service.RobotLogbackAppendService;
import com.zshy.base.monitor.domain.sender.factory.MonitorSendFactory;
import com.zshy.base.monitor.domain.sender.factory.Sender;
import com.zshy.base.monitor.domain.sender.factory.impl.DingDingRobotSender;
import com.zshy.base.monitor.domain.sender.factory.impl.QiWeiRobotSender;
import com.zshy.base.monitor.infras.properties.StarMonitorProperties;
import jakarta.annotation.Resource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.Objects;

/**
 * 日志告警配置
 *
 * @author zhouhengzhe
 */
@Configuration
@EnableConfigurationProperties(StarMonitorProperties.class)
@ConditionalOnClass(LoggerContext.class)
@ConditionalOnProperty(name = "zshy.base.monitor.log.enable", havingValue = "true", matchIfMissing = true)
public class BaseMonitorConfig {

    @Resource
    private StarMonitorProperties starMonitorProperties;


    @Bean
    public RobotLogbackAppendService robotLogbackAppendService() {
        return new RobotLogbackAppendService();
    }

    @Bean
    public Map<String, Sender> senderMap() {
        Map<String, Sender> map = Maps.newHashMap();
        if (Objects.nonNull(starMonitorProperties.getLog())) {
            if (Objects.nonNull(starMonitorProperties.getLog().getDingding())) {
                // 添加阿里云短信客户端
                DingDingRobotSender dingDingRobotSender = new DingDingRobotSender(starMonitorProperties.getLog().getDingding().getToken(),
                        starMonitorProperties.getLog().getDingding().getSecret());
                map.put(MonitorEnum.DING_TASK.getCode(), dingDingRobotSender);
            }else if (Objects.nonNull(starMonitorProperties.getLog().getQiwei())){
                 // 添加// 添加企微短信客户端
                QiWeiRobotSender qiWeiRobotSender = new QiWeiRobotSender(starMonitorProperties.getLog().getQiwei().getKey());
                map.put(MonitorEnum.QI_WEI.getCode(), qiWeiRobotSender);
            }
        }
        return map;
    }

    /**
     * 支持单项目单机器人（yml配置），多项目多机器人（请通过数据库配置）
     * @param senderMap
     * @return
     */
    @Bean
    public MonitorSendFactory smsServiceFactory(Map<String, Sender> senderMap) {
        return new MonitorSendFactory(senderMap);
    }
}